import { certiByPage, createCerti, paintCerti, toggleCerti, updateCerti } from '@/api/certi';
import { DATE_FORMAT_CN } from '@/utils';
import { getAccessToken } from '@/utils/cache';
import {
  certiMap,
  certiOptions,
  certiOptions2,
  certiStatusMap,
  certiStatusOptions,
  initDataAdapter,
  reqDataAdapter,
} from '@/utils/data';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Spin,
  Steps,
  Table,
  Upload,
  message,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';

export default () => {
  const [currentSteps, setCurrentSteps] = useState(0);
  const [updateOpen, setUpdateOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [createOpen2, setCreateOpen2] = useState(false);
  const [paintOpen, setPaintOpen] = useState(false);
  const [data, setData] = useState([]);
  const [searchVals, setSearchVals] = useState(null);
  const [currentPaint, setcurrentPaint] = useState('');
  const [editRow, setEditRow] = useState({});
  const [templateData, setTemplateData] = useState([]);
  const [createCertType, setCreateCertType] = useState(null);
  const [batchCreateVals, setBatchCreateVals] = useState(null);
  const [imgLoading, setImgLoading] = useState(false);

  const [searchForm] = Form.useForm();
  const [updateForm] = Form.useForm();
  const [createForm] = Form.useForm();
  const [batchCreateForm] = Form.useForm();

  const isQianfaType = (data) => data?.certType === 'jshyz' || data?.certType === 'hzdwz';

  const uploadProps = {
    name: 'file',
    action: 'https://zs.dance2020.cc:16063/admin-api/dcert/certificates/resolve',
    headers: {
      authorization: getAccessToken(),
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        console.log('[info]', info);
        setCurrentSteps(currentSteps + 1);
        setTemplateData(info?.file?.response?.data);
      } else if (info.file.status === 'error') {
        message.error(`文件解析失败，请重试`);
      }
    },
  };

  const columns = [
    {
      title: '颁发日期',
      dataIndex: 'issueDate',
      key: 'issueDate',
      render: (_) => {
        if (!_) return '暂无';
        return dayjs(_).format(DATE_FORMAT_CN);
      },
    },
    {
      title: '过期时间',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (expiryDate, record) => {
        if (!isQianfaType(record)) return '-';
        if (!expiryDate) return '暂无';
        // return expiryDate;
        const restDay = dayjs(expiryDate).diff(dayjs(record.issueDate), 'day');
        if (restDay < 0) return <div className="red">已过期</div>;
        if (restDay < 31) return <div className="red">{'剩余' + restDay + '天'}</div>;
        return '剩余' + restDay + '天';
      },
    },
    {
      title: '证书类型',
      dataIndex: 'certType',
      key: 'certType',
      render: (_) => {
        return certiMap[_] || '暂无';
      },
    },
    {
      title: '证书编号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      render: (_) => {
        return _ || '暂无';
      },
    },
    {
      title: '持有方',
      dataIndex: 'holderName',
      key: 'holderName',
      render: (_) => {
        return _ || '暂无';
      },
    },
    {
      title: '课程(活动)名',
      dataIndex: 'courseName',
      key: 'courseName',
      width: 125,
      render: (_) => {
        return _ || '-';
      },
    },
    {
      title: '证书状态',
      dataIndex: 'status',
      key: 'status',
      render: (_) => {
        return certiStatusMap[_] || '未知';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 230,
      render: (_, record) => {
        return (
          <div>
            <Button
              size="small"
              type="primary"
              className="ml10"
              onClick={() => {
                setUpdateOpen(true);
                let _row = initDataAdapter(record);
                // delete _row.issueDate
                console.log('[_row]', _row);
                setEditRow(_row);

                updateForm.resetFields();
                updateForm.setFieldsValue(_row);
              }}
            >
              编辑
            </Button>
            <Button
              className="ml10"
              size="small"
              type="primary"
              onClick={async () => {
                setPaintOpen(true);
                setImgLoading(true);
                const resp = await paintCerti({ id: record.certificateId });
                console.log('[resp]', resp);
                setcurrentPaint(`data:image/png;base64,${resp?.data}`);
              }}
            >
              查看证书
            </Button>
            {record.status === 0 && (
              <Button
                size="small"
                type="primary"
                className="ml10"
                danger
                onClick={async () => {
                  const resp = await toggleCerti({
                    certificateId: record.certificateId,
                    enabled: false,
                  });
                  if (resp.code === 0) {
                    message.success('操作成功');
                    // eslint-disable-next-line @typescript-eslint/no-use-before-define
                    init();
                  } else {
                    message.error(resp.msg);
                  }
                }}
              >
                下线
              </Button>
            )}

            {record.status === 2 && (
              <Button
                size="small"
                type="primary"
                className="ml10"
                onClick={async () => {
                  const resp = await toggleCerti({
                    certificateId: record.certificateId,
                    enabled: true,
                  });
                  if (resp.code === 0) {
                    message.success('操作成功');
                    // eslint-disable-next-line @typescript-eslint/no-use-before-define
                    init();
                  } else {
                    message.error(resp.msg);
                  }
                }}
              >
                上线
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  const columns2 = [
    {
      title: '证书编号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
    },
    {
      title: '证书类型',
      dataIndex: 'certType',
      key: 'certType',
      render: () => {
        return certiMap[batchCreateForm.getFieldValue('certType')] || '暂无';
      },
    },
    {
      title: '学员名称',
      dataIndex: 'holderName',
      key: 'holderName',
    },
    {
      title: '课程(活动)名称',
      dataIndex: 'courseName',
      key: 'courseName',
      render: (_) => {
        return batchCreateForm.getFieldValue('courseName') || '-';
      },
    },

    // {
    //   title: '操作',
    //   dataIndex: 'action',
    //   key: 'action',
    //   render: () => {
    //     return (
    //       <div>
    //         <Button type="primary">预览</Button>
    //       </div>
    //     );
    //   },
    // },
  ];

  const init = async () => {
    const resp = await certiByPage({
      pageNo: 1,
      pageSize: 100,
      ...(searchVals || {}),
    });
    console.log('😈resps', resp);
    setData(resp?.data?.list || []);
  };

  const search = async () => {
    const resp = await certiByPage({
      pageNo: 1,
      pageSize: 100,
      ...(searchVals || {}),
    });
    console.log('😈resps', resp);
    setData(resp?.data?.list || []);
  };

  const handleCreate = () => {
    createForm.validateFields({}).then(async () => {
      const values = createForm.getFieldsValue();
      const params = reqDataAdapter(values);
      params.baseInfos = [params.baseInfos];
      console.log('[params]', params);
      const resp = await createCerti(params);
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success('创建成功');
        setCreateOpen2(false);
        setCurrentSteps(0);
        createForm.resetFields();
        search();
      } else {
        message.error(resp.msg);
      }
    });
  };

  const batchCreate = () => {
    batchCreateForm.validateFields({}).then(async () => {
      const values = batchCreateVals;
      const params = reqDataAdapter(values);
      params.baseInfos = templateData;
      console.log('[params]', params);
      console.log('[templa]', templateData);
      const resp = await createCerti(params);
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success('批量创建成功');
        setCreateOpen(false);
        batchCreateForm.resetFields();
        setCurrentSteps(0);
        search();
      } else {
        message.error(resp.msg);
      }
    });
  };

  const handleUpate = () => {
    console.log('[editRow]', editRow);
    updateForm.validateFields({}).then(async () => {
      const values = updateForm.getFieldsValue();
      console.log('[values]', values);
      const resp = await updateCerti({
        ...reqDataAdapter(values),
        certificateId: editRow.certificateId,
      });
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success('编辑成功');
        search();
        setUpdateOpen(false);
        init();
      } else {
        message.error(resp.msg);
      }
    });
  };

  useEffect(() => {
    init();
  }, []);

  console.log('[createCertType]', createCertType);

  return (
    <PageContainer>
      <Modal
        title="编辑"
        open={updateOpen}
        onCancel={() => setUpdateOpen(false)}
        width={900}
        okText={'确认'}
        onOk={handleUpate}
      >
        <Card>
          <Form labelCol={{ span: 8 }} form={updateForm} initialValues={editRow}>
            <Row>
              <Col span={12}>
                <Form.Item name={'certType'} label="证书类型" rules={[{ required: true }]}>
                  <Select options={certiOptions} disabled></Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name={'serialNumber'} label="证书编号" rules={[{ required: true }]}>
                  <Input></Input>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="持有方" name={'holderName'} rules={[{ required: true }]}>
                  <Input></Input>
                </Form.Item>
              </Col>
              {/* <Col span={12}>
                <Form.Item label="性别" name={'holderKind'} rules={[{ required: true }]}>
                  <Select options={setOptions}></Select>
                </Form.Item>
              </Col> */}
              {!isQianfaType(editRow) && (
                <Col span={12}>
                  <Form.Item
                    label="课程(活动)名称"
                    name={'courseName'}
                    rules={[{ required: true }]}
                  >
                    <Input></Input>
                  </Form.Item>
                </Col>
              )}
              {editRow.certType === 'jyz' && (
                <>
                  <Col span={12}>
                    <Form.Item label="开始时间" name={'startTime'} rules={[{ required: true }]}>
                      <DatePicker className="w100"></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="结束时间" name={'endTime'} rules={[{ required: true }]}>
                      <DatePicker className="w100"></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="学时时长" name={'studyDuration'} rules={[{ required: true }]}>
                      <Input type="number"></Input>
                    </Form.Item>
                  </Col>
                </>
              )}
              {isQianfaType(editRow) && (
                <>
                  <Col span={12}>
                    <Form.Item
                      name={'birthDate'}
                      label="出生(成立)日期"
                      rules={[{ required: true }]}
                    >
                      <DatePicker className="w100" format={'YYYY-MM-DD'}></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name={'expiryDate'} label="有效期" rules={[{ required: true }]}>
                      <DatePicker className="w100" format={'YYYY-MM-DD'}></DatePicker>
                    </Form.Item>
                  </Col>
                </>
              )}
            </Row>
          </Form>
        </Card>
      </Modal>

      <Modal
        title={'查看证书'}
        width={'unset'}
        centered
        open={paintOpen}
        onCancel={() => {
          setPaintOpen(false);
          setcurrentPaint('');
        }}
        footer={null}
      >
        {imgLoading && (
          <div className="flex-center" style={{ height: '450px', minWidth: 300 }}>
            <Spin></Spin>
          </div>
        )}
        <div
          className="flex-center"
          style={{
            maxHeight: imgLoading ? 0 : undefined,
          }}
        >
          <img
            src={currentPaint}
            style={{ width: 'auto', height: '70vh' }}
            onLoad={() => setImgLoading(false)}
          ></img>
        </div>
      </Modal>

      <Modal
        title="创建"
        open={createOpen2}
        width={700}
        onCancel={() => {
          setCreateOpen2(false);
          setCurrentSteps(0);
          createForm.resetFields();
        }}
        footer={null}
      >
        <Steps
          current={currentSteps}
          items={[
            {
              title: '类型选择',
            },
            {
              title: '新建证书',
            },
          ]}
        />
        <Card
          className="mt20"
          bodyStyle={{
            minHeight: '450px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexDirection: 'column',
          }}
        >
          <Form
            labelCol={{ span: 7 }}
            className="w100 flex-center"
            form={createForm}
            onValuesChange={(_, avals) => {
              console.log('[avals]', avals);
              setCreateCertType(avals.certType);
            }}
          >
            <Form.Item name="certType" label="选择证书类型" hidden={currentSteps != 0} required>
              <Select style={{ width: '300px' }} options={certiOptions2}></Select>
            </Form.Item>
            {currentSteps === 1 && (
              <div className="flex flex-col" style={{ width: 500 }}>
                {createCertType === 'jyz' && (
                  <>
                    <Form.Item label="开始时间" name={'startTime'} required>
                      <DatePicker className="w100"></DatePicker>
                    </Form.Item>
                    <Form.Item label="结束时间" name={'endTime'} required>
                      <DatePicker className="w100"></DatePicker>
                    </Form.Item>
                    <Form.Item label="学时时长" name={'studyDuration'} required>
                      <Input type="number"></Input>
                    </Form.Item>
                  </>
                )}
                <Form.Item label="学员名称" name={['baseInfos', 'holderName']} required>
                  <Input></Input>
                </Form.Item>
                <Form.Item label="课程名称" name={'courseName'} required>
                  <Input></Input>
                </Form.Item>
                <Form.Item label="证书编号" name={['baseInfos', 'serialNumber']} required>
                  <Input></Input>
                </Form.Item>
                {/* <Form.Item label="证书过期时间">
                  <DatePicker className="w100"></DatePicker>
                </Form.Item> */}
              </div>
            )}
          </Form>

          <div className="flex-col flex-center mt10" style={{ marginTop: 30 }}>
            {currentSteps === 0 && (
              <div className="flex">
                <Button
                  type="primary"
                  onClick={() => {
                    if (!createForm.getFieldValue('certType')) {
                      message.error('请选择类型');
                      return;
                    }
                    setCurrentSteps(currentSteps + 1);
                  }}
                >
                  下一步
                </Button>
              </div>
            )}

            {currentSteps === 1 && (
              <div className="flex">
                <Button
                  type="primary"
                  onClick={() => {
                    setCurrentSteps(currentSteps - 1);
                  }}
                >
                  上一步
                </Button>
                <Button className=" ml10" type="primary" onClick={handleCreate}>
                  创建
                </Button>
              </div>
            )}
          </div>
        </Card>
      </Modal>

      <Modal
        title="批量创建"
        open={createOpen}
        footer={null}
        width={800}
        onCancel={() => {
          setCurrentSteps(0);
          setCreateOpen(false);
          batchCreateForm.resetFields();
        }}
      >
        <Steps
          current={currentSteps}
          items={[
            {
              title: '类型选择',
            },
            {
              title: '证书编辑',
            },
            {
              title: '导入学员',
            },
            {
              title: '结果预览',
            },
          ]}
        />
        <Card
          className="mt20"
          bodyStyle={{
            minHeight: '450px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexDirection: 'column',
          }}
        >
          <Form
            labelCol={{ span: 7 }}
            className="w100 flex-center"
            form={batchCreateForm}
            onValuesChange={(_, avals) => {
              console.log('[avals]', avals);
              setCreateCertType(avals.certType);
              setBatchCreateVals(avals);
            }}
          >
            <Form.Item name="certType" label="选择证书类型" hidden={currentSteps != 0} required>
              <Select style={{ width: '300px' }} options={certiOptions2}></Select>
            </Form.Item>
            {currentSteps === 1 && (
              <div className="flex flex-col" style={{ width: 500 }}>
                <Form.Item label="课程名称" name={'courseName'} required>
                  <Input></Input>
                </Form.Item>
                <>
                  <Form.Item
                    label="开始时间"
                    name={'startTime'}
                    required
                    hidden={createCertType !== 'jyz'}
                  >
                    <DatePicker className="w100"></DatePicker>
                  </Form.Item>
                  <Form.Item
                    label="结束时间"
                    name={'endTime'}
                    required
                    hidden={createCertType !== 'jyz'}
                  >
                    <DatePicker className="w100"></DatePicker>
                  </Form.Item>
                  <Form.Item
                    label="学时时长"
                    name={'studyDuration'}
                    required
                    hidden={createCertType !== 'jyz'}
                  >
                    <Input type="number"></Input>
                  </Form.Item>
                </>
              </div>
            )}
          </Form>

          {currentSteps === 2 && (
            <div className="flex-center w100">
              <Upload {...uploadProps}>
                <Button type="primary">请上传文件</Button>
              </Upload>
            </div>
          )}

          {currentSteps === 3 && (
            <Table className="w100 h100" columns={columns2} dataSource={templateData}></Table>
          )}
        </Card>

        {currentSteps !== 3 && (
          <div className="mt10 w100 flex-center mt10">
            {currentSteps !== 0 && (
              <Button
                className="mr10"
                type="primary"
                onClick={() => {
                  setCurrentSteps(currentSteps - 1);
                }}
              >
                上一步
              </Button>
            )}
            {
              <Button
                type="primary"
                onClick={() => {
                  if (!batchCreateForm.getFieldValue('certType')) {
                    message.error('请选择类型');
                    return;
                  }
                  setCurrentSteps(currentSteps + 1);
                }}
              >
                下一步
              </Button>
            }
          </div>
        )}

        {currentSteps === 3 && (
          <div className="mt10 w100 flex-center">
            <Button
              type="primary"
              onClick={() => {
                setCurrentSteps(currentSteps - 1);
              }}
            >
              上一步
            </Button>
            <Button className="ml10" type="primary" onClick={batchCreate}>
              生成
            </Button>
          </div>
        )}
      </Modal>

      <Card>
        <Form
          form={searchForm}
          onValuesChange={(_, vals) => {
            setSearchVals(vals);
          }}
        >
          <Row gutter={[10, -10]}>
            <Col span={6}>
              <Form.Item name={'issueDate'} style={{ marginBottom: 12 }}>
                <DatePicker.RangePicker
                  placeholder={['颁发日期开始', '颁发日期结束']}
                  className="w100"
                  format={'YYYY-MM-DD'}
                  allowClear
                ></DatePicker.RangePicker>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'expiryDate'} style={{ marginBottom: 12 }}>
                <DatePicker.RangePicker
                  format={'YYYY-MM-DD'}
                  allowClear
                  placeholder={['过期时间开始', '过期时间结束']}
                  className="w100"
                ></DatePicker.RangePicker>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'certType'} style={{ marginBottom: 12 }}>
                <Select
                  placeholder="请选择证书类型"
                  className="w100"
                  options={certiOptions}
                  allowClear
                ></Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'holderName'} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入持有方"></Input>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'serialNumber'}>
                <Input placeholder="请输入证书编号"></Input>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'courseName'}>
                <Input placeholder="请输入课程名"></Input>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'status'}>
                <Select
                  allowClear
                  placeholder="请选择证书状态"
                  className="w100"
                  options={certiStatusOptions}
                ></Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <div className="flex-bt">
          <div></div>
          <div>
            <Button type="primary" onClick={search}>
              搜索
            </Button>
            <Button type="primary" className="ml10" onClick={() => setCreateOpen2(true)}>
              创建
            </Button>
            <Button type="primary" className="ml10" onClick={() => setCreateOpen(true)}>
              批量创建
            </Button>
          </div>
        </div>
      </Card>

      <Card className="mt10">
        <Table columns={columns} dataSource={data}></Table>
      </Card>
    </PageContainer>
  );
};
